package org.fastsyncer.manager.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import org.apache.commons.io.serialization.ValidatingObjectInputStream;

public abstract class SerializableUtil {

	// 对象序列化过程
	public static void serializable(File file, Object obj) {
	    FileOutputStream out = null;
	    ObjectOutputStream oos = null;
        try {
            out = new FileOutputStream(file);
            if(out!=null){
                oos = new ObjectOutputStream(out);
                oos.writeObject(obj);
            }
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        } finally {
            if(oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                }
            }
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
	}

	// 对象反序列化过程
	public static Object deSerializable(File file) {
	    if(file==null){
	        return null;
	    }
	    Object readObject = null;
	    FileInputStream fis = null;
	    ValidatingObjectInputStream ois = null;
        try {
            fis = new FileInputStream(file);
            if(fis!=null){
                ois = new ValidatingObjectInputStream(fis);
                ois.accept("*");
//                ois.accept(new ClassNameMatcher() {
//                    @Override
//                    public boolean matches(String arg0) {
//                        return true; // 白名单classname
//                    }
//                });
                readObject = ois.readObject();
            }
        } catch (FileNotFoundException e) {
        } catch (ClassNotFoundException e) {
        } catch (IOException e) {
        } finally {
            if(ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                }
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
        return readObject;
	}

}
